using System;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;

namespace Sustainalytics.Portfolios.BL
{
    public interface IScreeningToolFilterManager
    {
        void RemovePortfolioFromScreeningToolFilters(Guid portfolioId);
        void UpdateFiltersFromScreeningTool(Guid portfolioId, Guid userId, string portfolioName);
    }

    public class ScreeningToolFilterManager : IScreeningToolFilterManager
    {
        private readonly IRepositoryCollection<Filter> _filterRepositoryCollection;

        public ScreeningToolFilterManager(IRepositoryCollection<Filter> filterRepositoryCollection )
        {
            _filterRepositoryCollection = filterRepositoryCollection;
        }


        public void UpdateFiltersFromScreeningTool(Guid portfolioId, Guid userId, string portfolioName)
        {
            var listFilters = _filterRepositoryCollection.ReadWhere(x => x.PortfolioId == portfolioId);
            foreach (var filter in listFilters)
            {
                if (filter.OwnerUserId != userId)
                {
                    RemovePortfolioFromScreeningToolFilters(filter);
                }
                else
                {
                    UpdateFilterNameFromScreeningTool(filter, portfolioName);
                }
            }
        }


        public void RemovePortfolioFromScreeningToolFilters(Guid portfolioId)
        {
            var listFilters = _filterRepositoryCollection.ReadWhere(x => x.PortfolioId == portfolioId);
            foreach (var filter in listFilters)
            {
                RemovePortfolioFromScreeningToolFilters(filter);
            }
        }

        private void RemovePortfolioFromScreeningToolFilters(Filter filter)
        {
            filter.PortfolioId = null;
            filter.PortfolioName = null;
            _filterRepositoryCollection.CreateOrUpdate(filter);
        }

        private void UpdateFilterNameFromScreeningTool(Filter filter, string portfolioName)
        {
            filter.PortfolioName = portfolioName;
            _filterRepositoryCollection.CreateOrUpdate(filter);
        }
    }
}